﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Weazel.Willows.Model
{
	public partial class SignalInConnector
		: SignalConnectorBase
	{
		private bool refined = false;

		private Weazel.Willows.RefinedModel.InPort port;
		public Weazel.Willows.RefinedModel.InPort Port
		{
			get { return port; }
		}

		public override void Refine(RefinedModel.Model model)
		{
			if (refined)
				return;

			refined = true;

			Module module = Parent as Module;
			Weazel.Willows.RefinedModel.Datapath datapath = module.Datapath;
			port = new Weazel.Willows.RefinedModel.InPort(TypeRegistry, datapath, LocalName, Type);

			if (datapath.InPorts.ContainsKey(port.LocalName))
			{
				string message = 
					string.Format("Cannot add port '{0}' to datapath '{1}. A port with that Name already exists.",
						port.LocalName, 
						datapath.Name
					);

				throw new ArgumentException(message);
			}


			if (this.Output is Signal)
			{
				Weazel.Gezel.Model.Expression updateExpr =
					new Weazel.Gezel.Model.BinaryExpression(
						Weazel.Gezel.Model.ExpressionType.Assignment,
						new Weazel.Gezel.Model.LeafExpression(Weazel.Gezel.Model.ExpressionType.Identifier, Output.LocalName),
						new Weazel.Gezel.Model.LeafExpression(Weazel.Gezel.Model.ExpressionType.Identifier, LocalName)
					);

				datapath.SignalFlowGraphs["always"].Expressions.Add(updateExpr);
			}
			datapath.InPorts.Add(port.LocalName, port);

			this.Input.Refine(model);
			this.Output.Refine(model);
		}
	}
}
